import { useEffect, useState } from 'react';
import cx from 'classnames';
import gs from '../../style/common.module.scss'
import s from './index.module.scss'

export enum SELECT_TYPE {
  SINGLE_SELECT, // 单选
  MULTIPLE_SELECT, // 多选
}

export const ListComp = ({ dataSource, renderRow, rowKey = 'id' }) => {
  return (
    <>
      {dataSource && dataSource.map((item, index) => renderRow(item, item[rowKey] || index, dataSource))}
    </>
  ) 
}

export const CheckboxWrap = ({ type = SELECT_TYPE.SINGLE_SELECT, rowKey = "id", value = null, onChange }) => {
  const [val, setVal] = useState<any>(null)

  useEffect(() => {
    setVal(value)
  }, [value])

  const handleChange = (e, item) => {
    let newValue = {};
    if (type === SELECT_TYPE.SINGLE_SELECT) {
      newValue = {
        [item[rowKey]]: item
      }
    } else if (type === SELECT_TYPE.MULTIPLE_SELECT) {
      newValue = val ? Object.assign({}, val) : {}
      if (!newValue[item[rowKey]]) {
        newValue[item[rowKey]] = item
      } else {
        delete newValue[item[rowKey]]
      }
    }

    setVal(newValue)
    onChange(newValue)
  }

  return (item, rowId, data) => {
    return (
      <a
        key={rowId}
        className={cx(s.checkBoxItem, gs.hcflex, { [s.active]: val && val[item[rowKey]] })}
        onClick={(e) => handleChange(e, item)}
      >
        {item.icon ? <img src={item.icon} /> : null}
        {item.label ? <span>{item.label}</span> : null}
      </a>
    )
  }
}